import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { userApi } from '../services/userService';

// 用户类型定义
export interface User {
  id: number;
  userName: string;
  userAvatar?: string;
  userRole: string;
  createTime: string;
  // 扩展用户属性
  nickname?: string;
  studentId?: string;
  gender?: string;
  userProfile?: string;
  grade?: string;
  college?: string;
  major?: string;
  researchDirection?: string;
  email?: string;
  phone?: string;
  qq?: string;
  wechat?: string;
  skills?: string;
}

// 登录参数接口
interface LoginParams {
  studentId: string;
  userPassword: string;
}

// 注册参数接口
interface RegisterParams {
  studentId: string;
  userPassword: string;
  checkPassword: string;
  email?: string;
  phone?: string;
}

// 用户状态接口
interface UserState {
  currentUser: User | null;
  isAuthenticated: boolean;
  loading: boolean;
  error: string | null;
}

// 初始状态
const initialState: UserState = {
  currentUser: null,
  isAuthenticated: false,
  loading: false,
  error: null,
};

// 登录异步thunk
export const loginUser = createAsyncThunk(
  'user/login',
  async (loginParams: LoginParams, { rejectWithValue }) => {
    try {
      const response = await userApi.login(loginParams);
      return response.data;
    } catch (error: any) {
      if (error.response && error.response.data) {
        return rejectWithValue(error.response.data.message || '登录失败');
      }
      return rejectWithValue('登录失败，请检查网络连接');
    }
  }
);

// 注册异步thunk
export const registerUser = createAsyncThunk(
  'user/register',
  async (registerParams: RegisterParams, { rejectWithValue }) => {
    try {
      const response = await userApi.register(registerParams);
      return response.data;
    } catch (error: any) {
      if (error.response && error.response.data) {
        return rejectWithValue(error.response.data.message || '注册失败');
      }
      return rejectWithValue('注册失败，请检查网络连接');
    }
  }
);

// 获取当前用户信息异步thunk
export const getCurrentUser = createAsyncThunk(
  'user/getCurrentUser',
  async (_, { rejectWithValue }) => {
    try {
      const response = await userApi.getCurrentUser();
      return response.data;
    } catch (error: any) {
      if (error.response && error.response.data) {
        return rejectWithValue(error.response.data.message || '获取用户信息失败');
      }
      return rejectWithValue('获取用户信息失败，请检查网络连接');
    }
  }
);

// 退出登录异步thunk
export const logoutUser = createAsyncThunk(
  'user/logout',
  async (_, { dispatch, rejectWithValue }) => {
    try {
      await userApi.logout();
      // 退出登录成功后清除状态
      dispatch(logout());
      return true;
    } catch (error: any) {
      if (error.response && error.response.data) {
        return rejectWithValue(error.response.data.message || '退出登录失败');
      }
      return rejectWithValue('退出登录失败，请检查网络连接');
    }
  }
);

// 用户切片
const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    logout: (state) => {
      state.currentUser = null;
      state.isAuthenticated = false;
      state.error = null;
    },
    clearError: (state) => {
      state.error = null;
    }
  },
  extraReducers: (builder) => {
    // 登录
    builder
      .addCase(loginUser.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(loginUser.fulfilled, (state, action: PayloadAction<User>) => {
        state.loading = false;
        state.isAuthenticated = true;
        state.currentUser = action.payload;
      })
      .addCase(loginUser.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
    
    // 注册
      .addCase(registerUser.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(registerUser.fulfilled, (state) => {
        state.loading = false;
      })
      .addCase(registerUser.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
    
    // 获取当前用户
      .addCase(getCurrentUser.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(getCurrentUser.fulfilled, (state, action: PayloadAction<User>) => {
        state.loading = false;
        state.isAuthenticated = true;
        state.currentUser = action.payload;
      })
      .addCase(getCurrentUser.rejected, (state) => {
        state.loading = false;
        state.isAuthenticated = false;
        state.currentUser = null;
      })
    
    // 退出登录
      .addCase(logoutUser.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(logoutUser.fulfilled, (state) => {
        state.loading = false;
      })
      .addCase(logoutUser.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  }
});

export const { logout, clearError } = userSlice.actions;
export default userSlice.reducer; 